package mysql

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
	"os"
	"time"
)

type Config struct {
	Addr       string
	User       string
	Password   string
	DbName     string
	Parameters string
	Debug      bool
}

//user:password@(addr)/dbname?charset=utf8&parseTime=True&loc=Local
func NewMysql(c *Config) (db *gorm.DB) {
	LogLevel := logger.Silent
	if c.Debug {
		LogLevel = logger.Info
	}
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags),
		logger.Config{
			SlowThreshold: time.Second,
			LogLevel:      LogLevel,
			Colorful:      false,
		},
	)
	dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?%s", c.User, c.Password, c.Addr, c.DbName, c.Parameters)
	var err error
	db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: newLogger,
	})
	if err != nil {
		panic(err)
	}
	return
}
